from flask import Flask, request, jsonify, render_template, send_from_directory
import os
import random

app = Flask(__name__)
UPLOAD_FOLDER = "uploads"
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 全局变量
verification_code = str(random.randint(1000, 9999))
file_cabinets = {}  # 存储文件柜信息 {cabinet_number: {"pickup_code": pickup_code, "file_path": file_path}}

@app.route("/")
def index():
    # 将验证码传递到前端
    return render_template("index.html", verification_code=verification_code)

@app.route("/verify", methods=["POST"])
def verify():
    user_code = request.json.get("code")
    if user_code == verification_code:
        cabinet_number = str(random.randint(1000, 9999))  # 生成随机文件柜编号
        return jsonify({"success": True, "message": "验证码正确！", "cabinet_number": cabinet_number})
    return jsonify({"success": False, "message": "验证码错误！"}), 400

@app.route("/upload", methods=["POST"])
def upload():
    cabinet_number = request.form.get("cabinet_number")
    if not cabinet_number:
        return jsonify({"success": False, "message": "文件柜编号缺失！"}), 400

    if "file" not in request.files:
        return jsonify({"success": False, "message": "未选择文件！"}), 400
    file = request.files["file"]
    if file.filename == "":
        return jsonify({"success": False, "message": "未选择文件！"}), 400

    # 保存文件并生成取件码
    pickup_code = str(random.randint(100000, 999999))
    file_path = os.path.join(UPLOAD_FOLDER, file.filename)
    file.save(file_path)

    # 保存文件柜信息
    file_cabinets[cabinet_number] = {"pickup_code": pickup_code, "file_path": file_path}

    return jsonify({
        "success": True,
        "message": f"文件上传成功！请记住以下信息：\n文件柜编号: {cabinet_number}\n取件码: {pickup_code}\n最长保管期为3天。",
    })

@app.route("/pickup", methods=["POST"])
def pickup():
    cabinet_number = request.json.get("cabinet_number")
    pickup_code = request.json.get("pickup_code")

    # 验证文件柜编号和取件码
    cabinet_info = file_cabinets.get(cabinet_number)
    if not cabinet_info:
        return jsonify({"success": False, "message": "文件柜编号错误！"}), 400
    if cabinet_info["pickup_code"] != pickup_code:
        return jsonify({"success": False, "message": "取件码错误！"}), 400

    return jsonify({"success": True, "message": "验证成功，请下载文件。"})


@app.route("/download/<cabinet_number>", methods=["GET"])
def download(cabinet_number):
    # 根据文件柜编号查找文件路径
    cabinet_info = file_cabinets.get(cabinet_number)
    if not cabinet_info:
        return jsonify({"success": False, "message": "文件柜编号错误！"}), 400

    file_path = cabinet_info["file_path"]
    if not os.path.exists(file_path):
        return jsonify({"success": False, "message": "文件不存在！"}), 404

    # 提取文件名
    filename = os.path.basename(file_path)

    # 发送文件并设置响应头
    return send_from_directory(
        directory=UPLOAD_FOLDER,
        path=filename,
        as_attachment=True,  # 强制浏览器下载文件
        download_name=filename  # 设置下载时的文件名
    )

if __name__ == "__main__":
    app.run(port=80, debug=True)